import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:orginone/components/XScaffold/XScaffold.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:scan/scan.dart';
import '../../config/theme/unified_style.dart';
import '../../dart/base/schema.dart';
import '../../dart/core/target/base/belong.dart';
import '../../main.dart';
import '../../routers/pages.dart';
import '../../routers/router_const.dart';
import '../../utils/system/PermissionUtil.dart';
import 'package:orginone/dart/core/thing/standard/form.dart' as core;
import 'package:orginone/dart/base/model.dart';
import '../XButton/XButton.dart';
import '../XImage/XImage.dart';
import '../form/form_widget/form_tool.dart';

class ScanWidget extends StatefulWidget {
  const ScanWidget({super.key});

  @override
  State<ScanWidget> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanWidget> {
  var platformVersion = '';

  var qrcode = '';

  final ImagePicker picker = ImagePicker();
  ScanController scanController = ScanController();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(
        alignment: Alignment.center,
        children: [
          scanView,
          Positioned(
            top: 40,
            left: 20,
            child: GestureDetector(
              onTap: (() {
                RoutePages.back(context);
              }),
              child: Container(
                margin: EdgeInsets.only(left: 20),
                child: XImage.localImage(XImage.iconWhiteleft, width: 8, height: 13),
              ),
            ),
          ),
          Positioned(
            top: 40,
            child: Text.rich(TextSpan(
              text: '扫一扫',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w600,
                  decoration: TextDecoration.none),
            )),
          ),
          Positioned(
            bottom: 35,
            child: XButton.iconCustomText(
              onPressed: chooseImage,
              icon: XImage.localImage(XImage.iconPhoto, width: 21.w, color: Colors.white),
              text: ' 相册',
              iconLeft: true,
              bgcolor: Colors.black26,
              textColor: Colors.white,
            ),
          ),
        ],
      ),
    );
    // return XScaffold(
    //   titleName: '扫一扫',
    //   backgroundColor: Colors.white,
    //   actions: [
    //     TextButton(
    //       child: const Text("相册"),
    //       onPressed: () => chooseImage(),
    //     ),
    //   ],
    //   body: scanView,
    // );
  }

  Widget get scanView => ScanView(
        controller: scanController,
        scanAreaScale: .7,
        scanLineColor: Colors.white60,
        onCapture: (data) => scanResult(data),
      );

  requestPermission() async {
    var status = await Permission.camera.status;
    if (status.isDenied) {
      PermissionUtil.showPermissionDialog(context, Permission.camera);
    }
  }

  chooseImage() async {
    try {
      var gallery = ImageSource.gallery;
      XFile? pickedImage = await picker.pickImage(source: gallery);
      if (pickedImage != null) {
        String? str = await Scan.parse(pickedImage.path);
        if (str != null) {
          // https://asset.orginone.cn/553616851498844161
          scanResult(str);
        } else {
          ToastUtils.showMsg(msg: '未识别到二维码');
        }
      }
    } on PlatformException catch (error) {
      if (error.code == "camera_access_denied") {
        PermissionUtil.showPermissionDialog(context, Permission.photos);
      }
    } catch (e) {
      ToastUtils.showMsg(msg: '打开相册时发生异常');
    }
  }

  scanResult(String data) async {
    qrcode = data;
    if (data.contains('https://')) {
      // 资产详情
      String id = data.toString().split('/').toList().last;
      XEntity? entity = await relationCtrl.user?.findEntityAsync(id);
      IBelong comp = relationCtrl.user!.currentSpace;
      if (entity == null) {
        String compid = comp.metadata.id;
        String? belongId = comp.metadata.belongId;
        List<String>? relations = comp.relations;
        Map data = await FormTool.getTargetcacheInfo(compid, belongId!, relations);
        if (null == data || data.length <= 0) {
          RoutePages.back(context);
          ToastUtils.showMsg(msg: comp.name + "下未扫到任何资产信息，请切换相应的个人/部门/单位进行查询");
        } else {
          if (data.toString().indexOf('MszhSetting') > 0) {
            Map mszhSetting = data['MszhSetting'];
            if (mszhSetting.containsKey('companyForm')) {
              Map<String, dynamic> scanForm = mszhSetting['scanForm'];
              late core.Form form = core.Form(XForm.fromJson(scanForm), comp.directory);
              List datas = await FormTool.loadFormDataById(id, comp);
              if (datas.isEmpty) {
                RoutePages.back(context);
                ToastUtils.showMsg(msg: comp.name + "下未扫到任何资产信息，请切换相应的个人/部门/单位进行查询");
              } else {
                var fm = FormTool.assembleData(datas[0], await form.loadFields());
                List<FieldModel> fmModels = fm.map((e) => FieldModel.fromJson(e)).toList();
                form.fields = fmModels;
                // Navigator.pop(context);
                RoutePages.back(context);
                RoutePages.to(path: Routers.formDetailPreview, data: form);
              }
            } else {
              RoutePages.back(context);
              ToastUtils.showMsg(msg: comp.name + "下未扫到任何资产信息，请切换相应的个人/部门/单位进行查询");
            }
          } else {
            Navigator.pop(context, data);
          }
        }
      } else {
        Navigator.pop(context, data);
      }
    } else {
      Navigator.pop(context, data);
    }
  }

  @override
  void dispose() {
    scanController.pause();
    super.dispose();
  }
}
